import React, { useState } from 'react';
import Taro from '@tarojs/taro';
import {AtIcon} from "taro-ui";
import {Image, View, Button} from '@tarojs/components'
import {
  GET_QRCODE_IMG,
  RESOURCE_URL, SHORT_URL,
  TARO_ENV
} from "../../constants/api";
import {getPoster, getPosterUrlForSeckillList} from "../../utils/poster.service";
import {http} from "../../utils/http";
import {user} from "../../utils/user.service";
import {newHttp} from "../../utils/request";
import './share.scss'

const Share: React.FC<{ displayPoster?: boolean; linkUri?: any; uuid?: any; type?: any; page?: any; isProduct?: boolean;onHandlerShowDialog?: any; isUser: any }> = (props) => {
  const [showDialog, setShowDialog] = useState(false);
  const [showLead, setShowLead] = useState(false);
  const [showPoster, setShowPoster] = useState(false);
  const [posterUrl, setPosterUrl] = useState('');
  const [showQrCode, setShowQrCode] = useState(false);
  const [qrCode, setQrCode] = useState('');
  const [shortLinkUri, setShortLinkUri] = useState('');

  const jumpHome = () => {
    if (TARO_ENV === 'h5') {
      window.location.href = window.location.origin + '/pages/my/index/index'
    } else {
      Taro.switchTab({url: '/pages/my/index/index'})
    }
  }

  const getPosters = async () => {
    if (!posterUrl) {
      Taro.showLoading({title: '获取海报中', mask: true})
      let poster
      if (props.page !== 'index') {
        if (props.page === 'seckillList') {
          // 秒杀活动列表
          poster = await getPosterUrlForSeckillList(props.uuid)
        }else {
          poster = await getPoster('polymerize', props.uuid, props.linkUri)
        }
      } else {
        poster = await getPoster('index', '', '') // 获取海报
      }
      Taro.hideLoading()
      if (!poster) {
        return false
      }
      setPosterUrl(poster.url || poster.data.url)
    }
    setShowPoster(true)
  }

  const imgClick = (img) => {
    Taro.previewImage({
      current: img,
      urls: [img]
    })
  }

  const savePhoto = async () => {
    if (TARO_ENV === 'h5') {
      return
    }
    Taro.showLoading({title: '保存中...'})
    await Taro.getImageInfo({
      src: posterUrl
    }).then(async (res) => { // 需要同步处理，否则会因为异步导致写入资源繁忙，无法保存
      await Taro.saveImageToPhotosAlbum({
        filePath: res.path,
      }).then(() => {
        Taro.hideLoading()
        Taro.showToast({title: '已保存1张图片'})
      }).catch(err => {
        Taro.hideLoading()
        console.log(err);
      })
    }).catch(err => {
      Taro.hideLoading()
      console.log(err);
    })
  }

  const getQrCode = async () => {
    if (!(await user.checkLogin())) {
      return user.jumpLogin()
    }
    if (!qrCode) {
      Taro.showLoading({mask: true, title: '加载中...'})
      let linkUri = props.linkUri
      if (TARO_ENV === 'h5') {
        let mpkey = ''
        const uInfo = Taro.getStorageSync('user') || ''
        if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
          mpkey = uInfo.mpkey
        }
        if (linkUri.indexOf('?') > -1) {
          linkUri = linkUri + '&mpkey=' + mpkey
        } else {
          linkUri = linkUri + '?mpkey=' + mpkey
        }
      }
      const posters = await http.carGet(GET_QRCODE_IMG, {pathUrl: linkUri || ''}) // 获取海报
      if (posters.codeImg) {
        setQrCode(posters.codeImg)
        Taro.hideLoading()
      }
    }
    setShowQrCode(true)
  }

  const shareNow = () => {
    setShowLead(true)
    setShowDialog(false)
  }

  const handlerShowDialog = () => {
    setShowDialog(true)
  }

  return (
    <View className='share-settings-components'>
      {process.env.SHOW_SHARE_POSTER && <View className='share-settings-components-logo' style={props.isProduct && 'bottom: calc(env(safe-area-inset-bottom) + 165px)'} onClick={() => handlerShowDialog()}>
        <Image mode='widthFix' className='share-settings-components-logo-img'
          src={RESOURCE_URL + `${props.isUser ? '/upload/images/20220214/1644819675105_281.png' : '/resources/weapp/images/202209/zhuan.png'}`}
        />
      </View>}
      <View className={`layout-customer ${showDialog && 'customer-layout-active'}`}>
        <View className='layout-customer__overlay' onClick={() => setShowDialog(false)} />
        <View className={`layout-customer-wrapper ${props.page === 'index' && 'long-height-bottom'}`}>
          <View className='layout-customer-wrapper-header'>
            <View className='layout-customer-wrapper-header-title'>
              立即分享给好友
            </View>
            <View className='layout-customer-close-btn' onClick={() => setShowDialog(false)}>
              <AtIcon value='close-circle' size='20' color='#c8c9cc' />
            </View>
          </View>
          <View>
            <View className='sm-icon-list-row'>
              {process.env.TARO_ENV !== 'h5' && <Button className='layout-btn-box-item share-button' openType='share'>
                <View className='share-text'><Image className='img' mode='aspectFill'
                  src='https://resource.ivcheng.com/resources/images/wx.png'
                /></View>
                <View className='sm-icon-list-row__name'>微信好友</View>
              </Button>}
              {process.env.TARO_ENV === 'h5' && <View className='layout-btn-box-item' onClick={() => {
                shareNow()
              }}
              >
                <Image className='img' mode='aspectFill' src='https://resource.ivcheng.com/resources/images/wx.png' />
                <View className='sm-icon-list-row__name'>微信好友</View>
              </View>
              }
              {process.env.TARO_ENV === 'h5' && <View className='layout-btn-box-item' onClick={async () => {
                let data = shortLinkUri
                if (!shortLinkUri) {
                  let linkUri = props.linkUri
                  let mpkey = ''
                  const uInfo = Taro.getStorageSync('user') || ''
                  if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
                    mpkey = uInfo.mpkey
                  }
                  if (linkUri.indexOf('?') > -1) {
                    linkUri = linkUri + '&mpkey=' + mpkey
                  } else {
                    linkUri = linkUri + '?mpkey=' + mpkey
                  }
                  const jsonObj = await newHttp.post(SHORT_URL, {longUrl: linkUri})
                  data = jsonObj.data
                  setShortLinkUri(data)
                }
                setTimeout(function () {
                  Taro.setClipboardData({
                    data
                  })
                  if (process.env.TARO_ENV === 'h5') {
                    Taro.showToast({title: '复制成功！'})
                  }
                }, 100);
                setShowDialog(false)
              }}
              >
                <Image className='img' mode='aspectFill'
                  src='https://resource.ivcheng.com/upload/images/20211029/1635504754889_760.png'
                />
                <View className='sm-icon-list-row__name'>复制链接</View>
              </View>}
              {props.displayPoster && <View className='layout-btn-box-item' onClick={async () => {
                await getPosters()
                setShowDialog(false)
              }}
              >
                <Image className='img' mode='aspectFill'
                  src='https://img01.yzcdn.cn/public_files/2017/08/29/2c62babaef58fea6f0f4e95e77c5b221.png'
                />
                <View className='sm-icon-list-row__name'>分享海报</View>
              </View>}
              <View className='layout-btn-box-item' onClick={async () => {
                await getQrCode()
                setShowDialog(false)
              }}
              >
                <Image className='img' mode='aspectFill'
                  src='https://resource.ivcheng.com/upload/images/20211029/1635504759396_831.png'
                />
                <View className='sm-icon-list-row__name'>{process.env.TARO_ENV === 'h5' ? '二维码' : '小程序码'}</View>
              </View>
              {TARO_ENV === 'weapp' && <View className='layout-btn-box-item' onClick={() => {
                jumpHome()
              }}
              >
                <Image className='img' mode='aspectFill'
                  src='https://resource.ivcheng.com/upload/images/20211029/1635504761744_259.png'
                />
                <View className='sm-icon-list-row__name'>店主中心</View>
              </View>}
              {TARO_ENV === 'h5' && !props.displayPoster && <View className='layout-btn-box-item' onClick={() => {
                jumpHome()
              }}
              >
                <Image className='img' mode='aspectFill'
                  src='https://resource.ivcheng.com/upload/images/20211029/1635504761744_259.png'
                />
                <View className='sm-icon-list-row__name'>店主中心</View>
              </View>}
            </View>
            {TARO_ENV === 'h5' && props.displayPoster && <View className='sm-icon-list-row sm-icon-list-row--border'>
              <View className='layout-btn-box-item' onClick={() => {
                jumpHome()
              }}
              >
                <Image className='img' mode='aspectFill'
                  src='https://resource.ivcheng.com/upload/images/20211029/1635504761744_259.png'
                />
                <View className='sm-icon-list-row__name'>店主中心</View>
              </View>
            </View>}
          </View>
        </View>
      </View>
      {showLead && <View className='share-lead'>
        <View className='share-guide'>
          <View className='share-guide__arrow' />
          <View className='share-guide-p-t'>
            <View className='share-guide__title'>立即分享给好友吧</View>
            <View className='share-guide__sub'>点击屏幕右上角将本页面分享给好友</View>
          </View>
        </View>
        <View className='share-guide-overlay' onClick={() => setShowLead(false)} />
      </View>}
      {(showQrCode || showPoster) && <View className='share-poster'>
        <View className='share-poster-bg' />
        <View className='share-poster-container'>
          <View className='share-poster-body'>
            <View onClick={() => {
              setShowQrCode(false)
              setShowPoster(false)
            }} className='share-poster-close'
            >
              <AtIcon value='close-circle' size='24' color='#fff' />
            </View>
            <View onClick={() => imgClick(showQrCode ? qrCode : posterUrl)}
              style={`${showQrCode && 'background: #fff; padding: 40px;'}`}
            >
              <Image className='gzh-close-img' src={showQrCode ? qrCode : posterUrl} mode='widthFix' />
            </View>
            {showPoster && <View className='saveToPhoto-box' onClick={() => savePhoto()}>
              {TARO_ENV === 'weapp' ? <View className='saveToPhoto'>保存到相册</View> :
                <View className='saveToPhoto'>请长按图片保存至相册</View>}
            </View>}
          </View>
        </View>
      </View>}
    </View>
  )
}

export default Share
